package com.zrm.zfcrpa.utils;

import com.alibaba.fastjson.JSONObject;
import com.zrm.zfcrpa.controller.HealthController;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MyJwtUtils {

    private Logger logger = LoggerFactory.getLogger(MyJwtUtils.class);

    private static String tokenSinkey = "zrmzfcrpa";
    //token有效时间：3小时
    private static long tokenExpiration = 3 * 60 * 60 * 1000L;

    public static String createToken(String username, String role, JSONObject object) {
        Map<String, Object> map = new HashMap<>();
        return Jwts.builder().setSubject(username)
                .claim("role", role)
                .claim("username", username)
                .claim("userObject", object)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS256, tokenSinkey).compressWith(CompressionCodecs.GZIP).compact();
    }

    /**
     * 解析token内的用户名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        Claims claims = MyJwtUtils.getClaims(token);
        String userName = (String) claims.get("username");
        return userName;
    }

    /**
     * 解析token内的角色信息
     *
     * @param token
     * @return
     */
    public static String getRole(String token) {
        Claims claims = MyJwtUtils.getClaims(token);
        String role = (String) claims.get("role");
        return role;
    }

    /**
     * 解析token内携带的用户信息
     *
     * @return
     */
    public static JSONObject userObject() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        if (token == null) {
            System.out.println("token不能为空");
            return null;
        }
        Claims claims = MyJwtUtils.getClaims(token);
        return (JSONObject) JSONObject.toJSON(claims.get("userObject"));
    }

    public static Claims getClaims(String token) {
        return Jwts.parser().setSigningKey(tokenSinkey).parseClaimsJws(token).getBody();
    }
}